package cn.itcast.goods.admin.book.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.book.domain.Book;
import cn.itcast.goods.book.service.BookService;
import cn.itcast.goods.category.doamin.Category;
import cn.itcast.goods.category.service.CategoryService;
import cn.itcast.servlet.BaseServlet;

public class AdminAddBookServlet extends HttpServlet {

	private CategoryService categoryService = new CategoryService();
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
	    DiskFileItemFactory factory = new DiskFileItemFactory();
	    ServletFileUpload sfu = new ServletFileUpload(factory);
	    
	    try {
			List<FileItem> itemLists = sfu.parseRequest(request);
			Book book = new Book(); //创建图书对象
			book.setBid(CommonUtils.uuid());
			book.setBname(itemLists.get(0).getString("uft-8"));//设置书名
			//获取大图的字段
			FileItem image_w= itemLists.get(1);
			//获取大图的上传路径
			String image_w_name = image_w.getName();
			//截取路径中的中文名称
			int index = image_w_name.lastIndexOf("\\");
			if(index > 0 )
			{
				image_w_name = image_w_name.substring(index)+1;
			}
			//检验文件的扩展名
			if(!image_w_name.toLowerCase().endsWith("jpg")&&!image_w_name.toLowerCase().endsWith("png")&&!image_w_name.toLowerCase().endsWith("bmp"))
			{
				Category category = new Category();
				request.setAttribute("parents", categoryService.findByParents());
				request.setAttribute("msg", "图片扩展名只能是jpg,png,bmp!");
				request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
				
			}
			
			//保存图片
			String bookSavePath = this.getServletContext().getRealPath("/book_img");
			image_w_name = CommonUtils.uuid()+"_"+image_w_name;
			File destFile = new File(bookSavePath, image_w_name);
			image_w.write(destFile);
			book.setImage_w("book_img/"+image_w_name);
			
			FileItem image_b = itemLists.get(2);
			//获取大图的上传路径
			String image_b_name = image_b.getName();
			//截取路径中的中文名称
			index = image_b_name.lastIndexOf("\\");
			if(index > 0)
			{
				image_b_name = image_b_name.substring(index+1);
			}
			//校验文件的扩展名
			if(!image_b_name.toLowerCase().endsWith("jpg")&&!image_w_name.toLowerCase().endsWith("png")&&!image_w_name.toLowerCase().endsWith("bmp"))
			{
				Category category = new Category();
				request.setAttribute("parents", categoryService.findByParents());
				request.setAttribute("msg", "图片扩展名只能是jpg,png,bmp!");
				request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
				
			}
			
			//保存图片
		    image_b_name = CommonUtils.uuid()+"_"+image_b_name;
		    destFile = new File(bookSavePath,image_b_name);
		    image_b.write(destFile);
		    book.setImage_b("book_img/"+image_b_name);
		    System.out.println("111111111111111111111111111");
		    book.setCurrPrice(Double.parseDouble(itemLists.get(3).getString()));
		    book.setPrice(Double.parseDouble(itemLists.get(4).getString()));
		    book.setDiscount(Double.parseDouble(itemLists.get(5).getString()));
		    book.setAuthor(itemLists.get(6).getString("utf-8"));
		    book.setPress(itemLists.get(7).getString("utf-8"));
		    book.setPublishtime(itemLists.get(8).getString("utf-8"));
		    book.setEdition(itemLists.get(9).getString("utf-8"));
		    book.setPageNum(Integer.parseInt(itemLists.get(10).getString("utf-8")));
		    book.setWordNum(Integer.parseInt(itemLists.get(11).getString("utf-8")));
		    book.setPrinttime(itemLists.get(12).getString("utf-8"));
		    book.setBooksize(Integer.parseInt(itemLists.get(13).getString("utf-8")));
		    book.setPaper(itemLists.get(14).getString("utf-8"));
		    
		    //设置2级分类
		    Category category = new Category();
		    String cid = itemLists.get(16).getString();
		    book.setCategory(category);
			
			//添加图书
		    BookService bookService = new BookService();
		    bookService.add(book);
		    request.setAttribute("msg", "添加图书成功！");
		    request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Category category = new Category();
			request.setAttribute("parents", categoryService.findByParents());
			
			if(e instanceof FileUploadBase.FileSizeLimitExceededException)
			{
				request.setAttribute("msg", "单个图片大小超出限制！");
				request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
				return;
			}
			if(e instanceof FileUploadBase.SizeLimitExceededException)
			{
				request.setAttribute("msg", "整个请求大小超出限制！");
				request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
				return;
			}
		
		}
	    
	}
}
